#! /bin/env python3
# coding: utf-8

import hashlib
import json
import uuid

import requests

from common.load_cfg import load_cfg
from common.my_mysql import get_data


class SendSMS:
    def __init__(self, team, local=False, phone_list=None):
        self.sms_info = load_cfg("sms_info")
        self.team = team
        self.local = local
        self.phone_list = phone_list

    def get_team_members(self):
        if self.local == False:
            sql = 'select phone from people_phone_sms where team = "{}"'.format(self.team)
            ywpt_n_9345 = load_cfg('ywpt_n_9345')
            data, num = get_data(ywpt_n_9345, sql)
            if num == 0:
                return "team is not exist"
            else:
                phones = []
                for phone in data:
                    phone_dict = {}
                    phone_dict['phone'] = phone[0]
                    phones.append(phone_dict)
                return phones
        else:
            return self.phone_list

    def send_sms(self, msg):
        headers = {"content-type": "application/json; charset=utf8"}
        url = self.sms_info['sms_url']
        params = {}
        params['account'] = self.sms_info['sms_user']
        params['content'] = msg
        params['list'] = []
        transaction_id = str(uuid.uuid4())
        hash_key = self.sms_info['sms_user'] + self.sms_info['sms_pass'] + transaction_id
        md5 = hashlib.md5()
        md5.update(hash_key.encode('utf8'))
        password = md5.hexdigest()
        params['transactionId'] = transaction_id
        params['password'] = password
        params['list'] = self.phone_list
        result = requests.post(url, data=json.dumps(params), headers=headers).text
        return (result)


if __name__ == '__main__':
    team = 'test'
    phone_list = [{'mobile': 13425198524}, {'mobile': 18565843088}]
    sms = SendSMS(team, local=True, phone_list=phone_list)
    msg = 'Hello World'
    result = sms.send_sms(msg)
    print(result)
